package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.AdvertDTO;
import com.financing.wap.dto.FpFundInfoDTO;
import com.financing.wap.dto.FpOrderPhoDTO;
import com.financing.wap.dto.FpShopperProductDTO;
import com.financing.wap.dto.FundLSJZJsonDTO;
import com.financing.wap.dto.MessageMailDTO;
import com.financing.wap.dto.OrderDTO;
import com.financing.wap.dto.ProductAnnualRevenueDTO;
import com.financing.wap.dto.ProductAttachmentDTO;
import com.financing.wap.dto.ProductBasicInfoDTO;
import com.financing.wap.dto.ProductDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.ProductRecommendDTO;
import com.financing.wap.dto.ProjectAccountDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAdvertService;
import com.financing.wap.service.IFpFundInfoService;
import com.financing.wap.service.IFpOrderPhoService;
import com.financing.wap.service.IFpShopperProductService;
import com.financing.wap.service.IMessageService;
import com.financing.wap.service.IOrderService;
import com.financing.wap.service.IProductOrderDataService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.JSONUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.AdvertVO;
import com.financing.wap.vo.ProductProfitAndRebateVO;
import com.financing.wap.vo.ProductVO;
import com.financing.wap.web.controller.BaseController;

/**
 * @author lisu
 * wap_jee_1.3
 * 	新增 大小配比类型 查询
 *  lisu
 */
@Controller("apiProductController")
@RequestMapping("/api/product")
public class ProductController extends BaseController {

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IProductService productService;
	@Autowired
	private IFpOrderPhoService fpOrderPhoService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IProductOrderDataService  productOrderDataService ;
	@Autowired
	private IAdvertService  advertServiceImpl;
	@Autowired
	private IUserService userService;
	@Autowired
	private IFpShopperProductService fpShopperProductService;

	@SuppressWarnings("unused")
	private String parameter;

	@Autowired
	private IFpFundInfoService fundInfoService;

	@Autowired
	private IMessageService messageService;
	
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	/**
	 * 展示所有产品列表
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, HttpServletResponse respons,Pager pager){
		UserDTO user = getSession(true).getUser();
		if(user==null){
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		try{
			//产品列表查询参数
			Map<String,Object> params = getProductQueryParams(request,respons);
			
			//店铺商品查询    直接新增返回是否添加标识
			String flagShopQuery = request.getParameter("flagShopQuery");
			String userId = user.getId();
			if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
				if(userId==null){
					result.setStatus(ResultMap.STATUS.NEED_LOGIN);
					result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
					return result;
				}
			}
			
			String pageNo = request.getParameter("pageNo");
			if(StringUtils.isBlank(pageNo)){
				pageNo="1";
			}
			int count = this.productService.getProductListCount(params, user);

			pager.setTotalCount(count);
			pager.setPageNo(Integer.parseInt(pageNo));

			log.info("------------>start time:"+SimpleDateFormat.getInstance().format(new Date()));

			List<ProductDTO> prodcutList = this.productService.getProductList(params, user,pager);
			if(null==prodcutList){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RETURNBOJECT_ERROR);
				result.setMessage("查询产品异常");
				return result;
			}
			
			if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
				String type = params.get("type")+"";
				//查询当前用户的所有标识
				fpShopperProductService.queryFlagShop(userId,type, prodcutList);
			}
			
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", prodcutList);
			result.setAttribute("pager", pager);
			result.setAttribute("fyFlag",getFYflag());
			log.info("---------------->end time:"+SimpleDateFormat.getInstance().format(new Date()));


			return result;
		}catch(Exception e){
			e.printStackTrace();
			log.error("error when query product list:",e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("查询产品异常");
			return result;
		}


	}
	/**
	 * 展示所有产品列表
	 * @return
	 */
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/pevcList")
	@ResponseBody
	public ResultMap pevcList(HttpServletRequest request, HttpServletResponse respons,Pager pager,ProductVO productVO){
	
		//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		
		UserDTO user = getSession(true).getUser();
		if(user==null){
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		try{
			log.info("In wap pevcList begin!");
			//店铺商品查询    直接新增返回是否添加标识
			String flagShopQuery = request.getParameter("flagShopQuery");
			String userId = user.getId();
			if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
				if(userId==null){
					result.setStatus(ResultMap.STATUS.NEED_LOGIN);
					result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
					return result;
				}
			}
			//参数添加
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("user", user);
			params.put("productVO", productVO);
			params.put("pager", pager);
			
			productVO.setStart(pager.getStartIndex());
			productVO.setPageSize(pager.getPageSize());
			
			int count = this.productService.getProductPEVCListCount(params);
			
			log.info("------------>start count:"+count);
			
			List<ProductDTO> prodcutList;
			pager.setTotalCount(count);

			log.info("------------>start time:"+SimpleDateFormat.getInstance().format(new Date()));
			if(count>0){
				prodcutList = this.productService.getProductPEVCList(params);
				if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
					String type = "06";
					//查询当前用户的所有标识
					fpShopperProductService.queryFlagShop(userId,type,prodcutList);
				}
			}else{
				prodcutList = Collections.EMPTY_LIST;
			}
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", prodcutList);
			result.setAttribute("pager", pager);
			
			log.info("---------------->end time:"+SimpleDateFormat.getInstance().format(new Date()));

			log.info("In wap pevcList end!");
			return result;
		}catch(Exception e){
			log.error("error pevcList:",e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("查询产品异常");
			return result;
		}

	}
	
	/**
	 * 展示所有产品列表
	 * @return
	 */
	@RequestMapping("/allProductList")
	@ResponseBody
	public ResultMap allProductList(HttpServletRequest request, HttpServletResponse respons,ProductVO productVO){
		UserDTO user = getSession(true).getUser();
		if(user==null){
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		try{
			//产品列表查询参数
			Map<String,Object> params = new HashMap<String, Object>();
			
			log.info("------------>start time:"+SimpleDateFormat.getInstance().format(new Date()));
			Pager pager=new Pager();
			pager.setPageNo(1);
			pager.setPageSize(3);
			params.put("type", "02");//产品类型
			params.put("pShortName", request.getParameter("pShortName"));//产品简称
			int countXT=this.productService.getProductListCount(params, user);
			List<ProductDTO> xintuoProdcutList = this.productService.getProductList(params, user,pager);
			
			params.put("type", "03");//产品类型
			params.put("pShortName", request.getParameter("pShortName"));//产品简称
			int countZG=this.productService.getProductListCount(params, user);
			List<ProductDTO> ziguanProdcutList = this.productService.getProductList(params, user,pager);
			
			params.put("pager", pager);
			productVO.setType("06");
			params.put("productVO", productVO);
			params.put("user", user);
			int countPEVC = this.productService.getProductPEVCListCount(params);
			List<ProductDTO> pevcProdcutList = this.productService.getProductPEVCList(params);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("countXT", countXT);
			result.setAttribute("countZG", countZG);
			result.setAttribute("countPEVC", countPEVC);
			result.setAttribute("xintuoProdcutList", xintuoProdcutList);
			result.setAttribute("ziguanProdcutList", ziguanProdcutList);
			result.setAttribute("pevcProdcutList", pevcProdcutList);
			log.info("---------------->end time:"+SimpleDateFormat.getInstance().format(new Date()));
			return result;
		}catch(Exception e){
			log.error("error when query allProductList list:" , e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("查询产品异常");
			return result;
		}
	}
	
	
	/**
	 * 展示所有产品列表
	 * @return
	 */
	@RequestMapping("/allProductListN")
	@ResponseBody
	public ResultMap allProductListN(HttpServletRequest request, HttpServletResponse respons,ProductVO productVO,Pager pager){
		UserDTO user = getSession(true).getUser();
		if(user==null){
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		String flagShopQuery = request.getParameter("flagShopQuery");
		String userId = user.getId();
		if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
			if(userId==null){
				result.setStatus(ResultMap.STATUS.NEED_LOGIN);
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				return result;
			}
		}
		try{
			String pTypeList=request.getParameter("pTypeList");
			//产品列表查询参数
			Map<String,Object> params = new HashMap<String, Object>();
			log.info("------------>start time:"+SimpleDateFormat.getInstance().format(new Date()));
			params.put("pShortName", request.getParameter("pShortName"));//产品简称
			params.put("pTypeList", "'02','03','06','07'");
			if(StringUtils.isNotBlank(pTypeList)){
				params.put("pTypeList", pTypeList);
			}
			//搜索页的查询  新增
			params.put("isnewCount","true");
			int count=this.productService.getProductListCount(params, user);
			pager.setTotalCount(count);
			List<ProductDTO> prodcutList = this.productService.getProductList(params, user,pager);


			if(StringUtils.isNotBlank(flagShopQuery)){
				//查询当前用户的所有标识
				fpShopperProductService.queryFlagShopForSearch(userId, prodcutList);
			}


			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("count", count);
			result.setAttribute("page", pager);
			result.setAttribute("prodcutList", prodcutList);
			result.setAttribute("fyFlag",getFYflag());
			log.info("---------------->end time:"+SimpleDateFormat.getInstance().format(new Date()));
			return result;
		}catch(Exception e){
			log.error("error when query allProductListN list:" , e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("查询产品异常");
			return result;
		}
	}
	
	@RequestMapping("/{productId}/view")
	@ResponseBody
	public ResultMap viewProductById(@PathVariable Integer productId){
		ResultMap result = new ResultMap();
		try {
			if(productId == null){
				logger.warn("==>error message:product is not exists");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("product is not exists");
			}else{
				ProductDetailPageDTO productDTO = productService.getProductDetailView(productId);				
				logger.info("=====view success====");
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("result", productDTO);
			}
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 展示产品详情
	 * @return
	 */
	@RequestMapping("/view/{productCode}")
	@ResponseBody
	public ResultMap viewProduct(@PathVariable String productCode,String code,String _pt,HttpServletRequest request){

		ResultMap result = new ResultMap();
		UserDTO user = getSession(true).getUser();
		try {
			if(!StringUtil.isNullOrEmptyStr(code)){
				productCode = code;
			}
			Integer id = productService.getProductIdByProductCode(productCode);
			if(id == null){
				logger.error("==>error message:product is not exists");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("product is not exists");
				return result;
			}else{
				ProductDetailPageDTO productDTO = productService.getProductDetailView(id);
				if(null==productDTO.getProductShortName()){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return result;
				}

				//机构内销产品，判断是否为所属机构
				if(Constants.FP_CORP_TYPE_PRIVATE.equals(productDTO.getCorpType())){
					if(null==user){//自由FA
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
						result.setMessage("product is not exists");
						return result;
					}
					String uType = user.getUType();//0：自由，1：机构用户，3：机构fa
					if(Constants.FA_TYPE_IFA.equals(uType)){//自由FA
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
						result.setMessage("product is not exists");
						return result;
					}
					if(Constants.FA_TYPE_CORP.equals(uType)&&!(user.getId().equals(productDTO.getCorpId()))){//机构账号
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
						result.setMessage("product is not exists");
						return result;
					}
					if(Constants.FA_TYPE_CORP_FA.equals(uType)&&(!user.getManagerId().equals(productDTO.getCorpId()))){//机构下属FA
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
						result.setMessage("product is not exists");
						return result;
					}
				}


				ProductAnnualRevenueDTO profit=productDTO.getProfit();
				//productDTO产品空判断
				if((user == null||"1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole()))&&profit!=null){
					profit.setRebate(null);
				}
				String summary = productDTO.getSummary();
				String titil="http://www-stg.superfa.cn";
				
				String replaceAll = summary.replaceAll(titil,"").replace("---输入内容---", "").replace("---输入内容--", "");

				productDTO.setSummary(replaceAll);
				
				if(StringUtils.isBlank(_pt)){
					_pt="pc";//默认认为pc
				}
				if(!"pc".equals(_pt)){//手机端  拆字段
					splitSummary(productDTO);
				}
				
				//判断是否为分销，如果分销则判断用户权限
				if(productDTO!=null && productDTO.getCorpType() == Constants.FP_CORP_TYPE_PRIVATE){
					//UserDTO user = getSession(true).getUser();
					if( !user.getManagerId().equals(productDTO.getCorpId()) &&!user.getId().equals(productDTO.getCorpId())){
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
						result.setMessage("product is not exists");
						return result;
					}
				}

				ProductAttachmentDTO attachment = new ProductAttachmentDTO();
				attachment.setpId(id);
				List<ProductAttachmentDTO> productAttachments = productService.getProductAttachments(attachment);
				//附件列表
				if(productAttachments==null){
					productAttachments = new ArrayList<ProductAttachmentDTO>();
				}
				
				
//				//查询上下架状态
//				String shopperId = request.getParameter("shopperId");
//				String keys = request.getParameter("keys");
//				if(!StringUtil.isNullOrEmptyNStr(productDTO.getProductCode(),productDTO.getProductType(),keys)){
//					
//					UserDTO loginUser = new UserDTO();
//					loginUser.setLoginName(shopperId);
//					loginUser = userService.queryUserLoginName(loginUser);
//					
//					FpShopperProductDTO shop=new FpShopperProductDTO();
//					shop.setProductId(productDTO.getProductCode());
//					shop.setProductType(productDTO.getProductType());
//					shop.setUserId(loginUser.getId());
//					FpShopperProductDTO shopperProductDto = fpShopperProductService.queryListGetFirst(shop);
//					if(shopperProductDto.getProductState()!=null && shopperProductDto.getProductState()!=1){
//						result.setStatus(STATUS.ERROR);
//						result.setStatusCode(ResultMap.PRODUCT_DOWN);
//					}
//				}
				
				
				productDTO.setProductAttachments(productAttachments);
				logger.info("=====view success====");
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("result", productDTO);
				result.setAttribute("fyFlag",getFYflag());
				return result;
			}
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}

	/**
	 * 展示更多产品详情
	 * @return
	 */
	@RequestMapping("/more/{productCode}")
	@ResponseBody
	public ResultMap moreProduct(@PathVariable String productCode,Model model){

		ResultMap result = new ResultMap();
		try {
			Integer id = productService.getProductIdByProductCode(productCode);
			if(id == null){
				logger.error("==>error message:product is not exists");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setMessage("product is not exists");
			}else{
				ProductDetailPageDTO productDTO = productService.getProductDetailView(id);		
				logger.info("=====view success====");
				result.setStatus(STATUS.SUCCESS);
				result.setAttribute("result", productDTO);
			}
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}


	/**
	 * 展示某一分类下的产品列表
	 * @param type
	 * @return
	 */
	@RequestMapping("/{type}/list")
	@ResponseBody
	public ResultMap list(@PathVariable String type, Pager pager){

		ResultMap result = new ResultMap();
		try{
			Map<String,Object> queryParams = new HashMap<String,Object>();
			UserDTO user = getSession(true).getUser();
			queryParams.put("type", type);
			List<ProductDTO> prodcutList = this.productService.getProductList(queryParams,user,pager);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", prodcutList);
			result.setAttribute("pager", pager);
			return result;
		}catch(Exception e){
			log.error("error when query product list:" + e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setMessage("查询产品列表异常");
			return result;
		}
	}

	/**
	 * 展示推荐产品
	 * @return
	 */
	@RequestMapping("/recommend")
	@ResponseBody
	public ResultMap recommendAPI(HttpServletRequest request, HttpServletResponse respons){
		ResultMap result = new ResultMap();
		try{
			UserDTO userDTO = getSession(true).getUser();
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			if(userDTO == null){
				queryMap.put("faId", null);
				userDTO = new UserDTO();
				userDTO.setUType("0");
				queryMap.put("user", userDTO);
			}else{
				queryMap.put("faId", userDTO.getId());
				queryMap.put("user", userDTO);
			}
			
			String productType=request.getParameter("productType");
			if(StringUtils.isNotBlank(productType)){
				queryMap.put("productType", "('02','03')");
			}


			String size = request.getParameter("size");
			if(StringUtils.isBlank(size)){
				size="1";
			}
			queryMap.put("size", Integer.parseInt(size));

			List<ProductDetailPageDTO> dtoList = this.productService.getRecommendProduct(queryMap);
			//Map<String, Object> paramMap = BeanUtil.transBean2Map(dto);
			List<ProductRecommendDTO>  fundRecommendList = this.productService.getRecommendFundProduct();
			// FpFundInfoDTO
			List<FpFundInfoDTO>  fundList = new ArrayList<FpFundInfoDTO>();
			FpFundInfoDTO fpFundInfo = null;
			int temp = -1;
			if(null != fundRecommendList){
				for (int i = 0; i < fundRecommendList.size() ; i++) {
					// 查询私募信息
					fpFundInfo = fpFundInfoService.getFpFundInfo(fundRecommendList.get(i).getFpProjectId());
					// 历史最高净值
					try {
						List<FundLSJZJsonDTO> fundLSJZJ = (List<FundLSJZJsonDTO>) JSONArray.toCollection(JSONArray.fromObject(fpFundInfo.getLsjzJson()), FundLSJZJsonDTO.class);
						if(null !=fundLSJZJ.get(0) && null != fundLSJZJ && fundLSJZJ.size() > 0){
							temp = Integer.parseInt(fundLSJZJ.get(0).getJzdw());
							for (int j = 0; j < fundLSJZJ.size(); j++) {
								if(temp < Integer.parseInt(fundLSJZJ.get(i).getJzdw())){
									temp = Integer.parseInt(fundLSJZJ.get(i).getJzdw());
								}
							}
							if(temp != -1){
								fpFundInfo.setZgjz(temp);
							}
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
					if("1".equals(fpFundInfo.getPubStatus())){
						fundList.add(fpFundInfo);
					}
				}
			}
			result.setAttribute("fundList", fundList);
			result.setAttribute("list", dtoList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			log.error("recommend error:",e);
		}
		
		return result;
	}

	/**
	 *mediaSourceProduct 产品
	 * @return
	 */
	@RequestMapping("/mediaSourceProductList")
	@ResponseBody
	public ResultMap mediaSourceProductList(HttpServletRequest request, HttpServletResponse respons){
		ResultMap result = new ResultMap();
		try{
			String mediaSource = request.getParameter("mediaSource");
			if(StringUtils.isBlank(mediaSource)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("mediaSource",mediaSource);
			String size = request.getParameter("size");
			if(StringUtils.isBlank(size)){
				size="1";
			}
			queryMap.put("size", Integer.parseInt(size));

			List<Map<String,Object>> dtoList = this.productService.getMediaSourceProduct(queryMap);

			result.setAttribute("list", dtoList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			log.error("recommend error:",e);
		}
		
		return result;
	}

	/**
	 * 组装产品列表查询参数
	 * @param request
	 * @param respons
	 * @return
	 */
	private Map<String,Object> getProductQueryParams(HttpServletRequest request, HttpServletResponse respons){

		//结款节点
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("type", request.getParameter("type"));
		params.put("pPaymentInterestType", request.getParameter("pPaymentInterestType"));//付息方式
		params.put("pInvestType", request.getParameter("pInvestType"));//投资类型
		params.put("pPublicArea", request.getParameter("pPublicArea"));//所在地区
		params.put("pBelongArea", request.getParameter("pBelongArea"));//所属地区
		params.put("pLevel", request.getParameter("pLevel"));//产品评级
		params.put("minimumAmount", request.getParameter("minimumAmount"));//起购金额
		params.put("pShortName", request.getParameter("pShortName"));//产品简称
		params.put("pSizeRatioType", request.getParameter("pSizeRatioType"));//产品简称
		params.put("saleStatus", request.getParameter("saleStatus")); //产品销售状态
		
		params.put("pRabateProfitParameter", request.getParameter("pRabateProfitParameter"));//返佣
		params.put("pAnnualRevenueExpectParameter", request.getParameter("pAnnualRevenueExpectParameter"));//年化率
		params.put("hasBidding", request.getParameter("hasBidding"));// 1 个人   2官网
		//添加排序方式
		getProductOrderType( request.getParameter("orderParameter"), request.getParameter("orderType"),params);

		String dueTime = request.getParameter("dueTime");//产品期限
		Map<String,Object> dueTimeMap = CommonConstantUtil.dueTimeUtils(dueTime);
		Iterator<String>  dtkeySetIterator = dueTimeMap.keySet().iterator();
		while (dtkeySetIterator.hasNext()) {
			String key = dtkeySetIterator.next();
			params.put(key, dueTimeMap.get(key));
		}
		String annualRevenue = request.getParameter("annualRevenue");//收益
		Map<String,Object> annualRevenueMap = CommonConstantUtil.annualRevenueUtils(annualRevenue);
		Iterator<String>  arkeySetIterator = annualRevenueMap.keySet().iterator();
		while (arkeySetIterator.hasNext()) {
			String key = arkeySetIterator.next();
			params.put(key, annualRevenueMap.get(key));
		}
		
		return params;
	}
	/**
	 * 排序方式，将参数转化成数据库参数
	 * @param
	 * @return
	 */
	private void  getProductOrderType(String orderParameter,String orderType,Map<String,Object> params){
		if(StringUtil.isNullOrEmptyStr(orderParameter)){
			return;
		}
		//01 投资期限 02 付息方式
 		if("01".equals(orderParameter)){
 			params.put("orderParameter", "P_DUE_TIME");
 		}else if("02".equals(orderParameter)){
 			params.put("orderParameter", "P_PAYMENT_INTEREST_TYPE");
 		}
 		//01 降序 02 升序
 		if("01".equals(orderType)){
 			params.put("orderType", "desc");
 		}else if("02".equals(orderType)){
 			params.put("orderType", "asc");
 		}else{
 			params.put("orderType", "desc");
 		}
		
	}


	/**
	 * 展示产品账户信息
	 * @return
	 */
	@RequestMapping("/account")
	@ResponseBody
	public ResultMap accountAPI(String productId){
		ResultMap result = new ResultMap();

		List<ProjectAccountDTO> projectAccountList = this.productService.queryProjectAccount(Integer.valueOf(productId));

		result.setAttribute("projectAccountList",projectAccountList);
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		return result;
	}
	/**
	 * 首页展品数据显示 amountCount
	 * @return
	 */
	@RequestMapping("/amountCount")
	@ResponseBody
	public ResultMap amountCount(HttpServletRequest request, HttpServletResponse respons){
		ResultMap result = new ResultMap();
		try{
			log.info("product amountCount begin!");
			
			Map<String,Integer> amountCount = this.productService.queryProjectAmountCount();
			result.setAttribute("amountCount", amountCount);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			
			log.info("product amountCount end!");
		}catch(Exception e){
			log.error("amountCount error:",e);
		}
		
		return result;
	}
	
	/**
	 * 三件套上传
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addFpOrderPho")
	@ResponseBody
	public ResultMap addFpOrderPho(HttpServletRequest request,HttpServletResponse response,String json,String oId){
		ResultMap result=new ResultMap();
		
		try{
			log.info("product addFpOrderPho begin");
			
			OrderDTO orderDTO =  orderService.getOrder(oId);
			if(orderDTO == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("OrderDTO is not exists");
				return result;
			}
			ProductDetailPageDTO productDTO = productService.getProductDetailView(orderDTO.getPid());
			if(productDTO == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("product is not exists");
				return result;
			}
			UserDTO userDTO = getSession(true).getUser();
			if(userDTO == null){
				result.setStatus(STATUS.NEED_LOGIN);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("Need login");
				result.setAttribute(Constants.ResultMessage,"未登录,请先登录");
				return result;
			}
			
			List<FpOrderPhoDTO> lis  = (List<FpOrderPhoDTO>) JSONUtil.getListForJson(json, FpOrderPhoDTO.class);
				
			fpOrderPhoService.addFpOrderPho(lis,productDTO,oId,userDTO.getId());
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					
			log.info("product addFpOrderPho end");
			
		}catch(Exception e){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			log.error("addFpOrderPho action error:",e);
		}
		return result;
	}
	
	/**
	 * 根据订单号查询产品号，资料上传情况
	 */
	@RequestMapping("/findFpOrderPhos")
	@ResponseBody
	public ResultMap findFpOrderPhos(HttpServletRequest request,HttpServletResponse response,FpOrderPhoDTO fpd){
		ResultMap result=new ResultMap();
		try{
		log.info("product findFpOrderPhos begin");
		
		List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);
		
		//默认状态为未提交审核
		String phoStatus = Constants.order_data_pho_rev_no;
		Map<String,String> map = new HashMap<String,String>();
		for(FpOrderPhoDTO PODtmp  : PODList){
			
			if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
				map.put("01", "01");
				continue;
			}
			map.put(PODtmp.getoPhoStatus(), "01");
			
		}
		
		if(map.containsKey(Constants.order_data_pho_rev_no)){
			
			 phoStatus = Constants.order_data_pho_rev_no;
		}else
		if(map.containsKey(Constants.order_data_pho_rev_fail)){
			
			 phoStatus = Constants.order_data_pho_rev_fail;
		}else
		if(map.containsKey(Constants.order_data_pho_rev_yes)){
			
			 phoStatus = Constants.order_data_pho_rev_yes;
		}else
		if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
			
			 phoStatus = Constants.order_data_pho_rev_success;
		}
		
	
		
		result.setAttribute("phoStatus", phoStatus);
		result.setAttribute("PODList", PODList);
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		log.info("product findFpOrderPhos end");
		}catch(Exception e){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			log.error("findFpOrderPhos action error:",e);
		}
		return result;
	}
	
	/**
	 * 根据订单号查询资料上传情况
	 */
	@RequestMapping("/findFpOrderPhoResult")
	@ResponseBody
	public ResultMap findFpOrderPhoResult(HttpServletRequest request,HttpServletResponse response,FpOrderPhoDTO fpd){
		ResultMap result=new ResultMap();
		try{
		log.info("product findFpOrderPhos begin");
		FpOrderPhoDTO fopd=fpOrderPhoService.findFpOrderPhoResult(fpd);
		result.setAttribute("fopd", fopd);
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		log.info("product findFpOrderPhos end");
		}catch(Exception e){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			log.error("findFpOrderPhos action error:",e);
		}
		return result;
	}
	
	/**
	 * 显示资料是否审核通过（如果全部审核通过就返回true，如果有一项还未审核通过就返回false，表示资料未审核）
	 */
	@RequestMapping("/checkFpOrderPhoStatus")
	@ResponseBody
	public ResultMap checkFpOrderPhoStatus(HttpServletRequest request,HttpServletResponse response,FpOrderPhoDTO fpd){
		ResultMap result=new ResultMap();
		try{
		log.info("product findFpOrderPhos begin");
		Boolean checkStatus=fpOrderPhoService.checkFpOrderPhoStatus(fpd);
		result.setAttribute("checkStatus", checkStatus);
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		log.info("product checkFpOrderPhoStatus end");
		}catch(Exception e){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			log.error("checkFpOrderPhoStatus action error:",e);
		}
		return result;
	}
	
	
	
	/**
	 *热搜榜
	 */
	@RequestMapping("/heightSearch")
	@ResponseBody
	public ResultMap heightSearch(HttpServletRequest request,HttpServletResponse response){
		ResultMap result=new ResultMap();
		List<ProductDetailPageDTO>list =new ArrayList<ProductDetailPageDTO>();
		try{
			Object  mapObjecct = MemcacheCacheHelper.mcc.get("productName_map");
			if(mapObjecct != null && mapObjecct instanceof Map){
				Map<Integer,Integer> pMap = (HashMap<Integer,Integer>)MemcacheCacheHelper.mcc.get("productName_map");
				//遍历还是需要拿一个容器存储然后排序。
				Map<Integer, Integer> sortMap = sortMapByValue(pMap);
				Iterator entries = sortMap.entrySet().iterator();
				  int i=0;
				while (entries.hasNext()) {  
				  
				    Map.Entry entry = (Map.Entry) entries.next();  
				    
				    Integer key = (Integer)entry.getKey();  
				    i++;
				    //查询产品详情
				    
				    ProductDetailPageDTO productDto = productService.getProductDetailView(key);
				    if(key!=null){
				    	list.add(productDto);
				    }
				    
				    if(i==4)
				    break;
				}  
			}
			
		log.info("product heightSearch begin");
		result.setStatus(STATUS.SUCCESS);
		result.setAttribute("list", list);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		log.info("product heightSearch end");
		}catch(Exception e){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			log.error("heightSearch action error:",e);
		}
		return result;
	}	
	
	/**
	 * app改版首页广告位的展示2015-10-20
	 * @param request
	 * @param response
	 * @param advertDTO
	 * 
	 */
	
	@RequestMapping("/queryAdvertLists")
	@ResponseBody
	public ResultMap queryAdvertLists(HttpServletRequest request,
			HttpServletResponse response,AdvertVO advertDTO) {
		ResultMap resultMap=new ResultMap();
		log.info("In AdvertAction queryAdvertList Begin!");
		
		try{
			List<AdvertDTO>list = advertServiceImpl.queryAdvertLists(advertDTO);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			resultMap.setAttribute("list", list);
		}catch(Exception e){
			log.error("AdvertAction queryAdvertList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
			
		log.info("In AdvertAction queryAdvertList end!");
		return resultMap;
	}
	
	
	//对排名排序
	public  Map<Integer, Integer> sortMapByValue(Map<Integer, Integer> oriMap) {  
	    Map<Integer, Integer> sortedMap = new LinkedHashMap<Integer, Integer>();  
	    if (oriMap != null && !oriMap.isEmpty()) {  
	        List<Map.Entry<Integer, Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>(oriMap.entrySet());  
	        Collections.sort(entryList,  
	                new Comparator<Map.Entry<Integer, Integer>>() {  
	                    public int compare(Entry<Integer, Integer> entry1,  
	                            Entry<Integer, Integer> entry2) {  
	                        int value1 = 0, value2 = 0;  
	                        try {  
	                            value1 = entry1.getValue();  
	                            value2 = entry2.getValue();  
	                        } catch (NumberFormatException e) {  
	                            value1 = 0;  
	                            value2 = 0;  
	                        }  
	                        return value2 - value1;  
	                    }  
	                });  
	        Iterator<Map.Entry<Integer, Integer>> iter = entryList.iterator();  
	        Map.Entry<Integer, Integer> tmpEntry = null;  
	        while (iter.hasNext()) {  
	            tmpEntry = iter.next();  
	            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());  
	        }  
	    }  
	    return sortedMap;  
	}  
	

	/**
	 * 展示某类型下所有产品列表
	 * 
	 * @return
	 */
	@RequestMapping("/listByType")
	@ResponseBody
	public ResultMap listByType(HttpServletRequest request,
			HttpServletResponse respons, String pType) {
		UserDTO user = getSession(true).getUser();
		if (user == null) {
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		try {
			// 产品列表查询参数
			log.info("------------>start time:"
					+ SimpleDateFormat.getInstance().format(new Date()));

			if (StringUtils.isBlank(pType)) {
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("查询产品参数缺失");
				return result;
			}
			List<ProductDTO> prodcutList = null;
			if ("05".equals(pType)) {
				prodcutList = this.fundInfoService.listFpFundInfoByType();
			} else {
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("pType", pType);
				prodcutList = this.productService.getProductByType(params);
			}
			if (null == prodcutList) {
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RETURNBOJECT_ERROR);
				result.setMessage("查询产品异常");
				return result;
			}
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", prodcutList);
			log.info("---------------->end time:"
					+ SimpleDateFormat.getInstance().format(new Date()));
			return result;
		} catch (Exception e) {
			log.error("error when query product list:" + e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("查询产品异常");
			return result;
		}

	}

	/**
	 * 展示某类型下所有产品列表
	 * 
	 * @return
	 */
	@RequestMapping("/detailByType")
	@ResponseBody
	public ResultMap detailByType(HttpServletRequest request,
			HttpServletResponse respons, String code) {

		ResultMap result = new ResultMap();
		UserDTO user = getSession(true).getUser();
		try {
			if (StringUtils.isBlank(code)) {
				logger.info("==>warn messang:STATUS_CODE_PARAMETERS_LOSE ");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			ProductDetailPageDTO productDTO = getXintuoDetail(code, result,
					user);
			if (productDTO == null) {
				return result;
			}
			

			// //拆分字段
			// HashMap<String, String> hm=new HashMap<String, String>();
			// try {
			// String tmp2 =
			// productDTO.getSummary().replaceAll("<[^a].*?>|募集账号：|产品优势：|风险控制：|还款来源：|资金用途：|融资方：|担保方：|募集账号|产品优势|风险控制|还款来源|资金用途|融资方|担保方",
			// "")+"<a na";
			// List<String> fecthAll =StringUtil.fecthAll(tmp2,
			// "me=[\"'](.*?)[\"']>(.*?)<a na",2,true);
			// for (int i = 0; i < fecthAll.size(); i++) {
			// hm.put(fecthAll.get(i).split("====")[0],fecthAll.get(i).split("====").length>=2?fecthAll.get(i).split("====")[1]:"");
			// }
			// productDTO.setSummary(JSONArray.toJSONString(hm));
			// } catch (Exception e) {
			// log.error("summary error",e);
			// productDTO.setSummary("");
			// }

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", productDTO);
			return result;
		} catch (Exception e) {
			logger.warn("==>warn messang:" + e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}

	}

	/**
	 * 
	 * 
	 * @Title: getXintuoDetail
	 * 
	 * @Description:信托资管产品详情查询
	 * 
	 * @param @param productCode
	 * @param @param result
	 * @param @param user
	 * @param @return
	 * @param @throws Exception 设定文件
	 * 
	 * @return ProductDetailPageDTO 返回类型
	 * 
	 * @throws
	 */
	public ProductDetailPageDTO getXintuoDetail(String productCode,
			ResultMap result, UserDTO user) throws Exception {
		Integer id = productService.getProductIdByProductCode(productCode);
		if (id == null) {
			logger.error("==>error message:product is not exists");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
			result.setMessage("product is not exists");
			return null;
		} else {
			ProductDetailPageDTO productDTO = productService
					.getProductDetailView(id);
			if (null == productDTO.getProductShortName()) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("product is not exists");
				return null;
			}

			// 机构内销产品，判断是否为所属机构
			if (Constants.FP_CORP_TYPE_PRIVATE.equals(productDTO.getCorpType())) {
				if (null == user) {// 自由FA
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return null;
				}
				String uType = user.getUType();// 0：自由，1：机构用户，3：机构fa
				if (Constants.FA_TYPE_IFA.equals(uType)) {// 自由FA
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return null;
				}
				if (Constants.FA_TYPE_CORP.equals(uType)
						&& (!user.getId().equals(productDTO.getCorpId()))) {// 机构账号
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return null;
				}
				if (Constants.FA_TYPE_CORP_FA.equals(uType)
						&& !(user.getManagerId().equals(productDTO.getCorpId()))) {// 机构下属FA
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return null;
				}
			}
			ProductAnnualRevenueDTO profit = productDTO.getProfit();
			//未登陆 删除返佣金额
			boolean b = user==null||user.getId() == null||"1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole());
			if (b && profit != null) {
				profit.setRebate(null);
			}
			ProductAnnualRevenueDTO profitHight = productDTO.getProfitHight();
			//未登陆 删除返佣金额
			if (b && profitHight != null) {
				profitHight.setRebate(null);
			}
			
			List<ProductProfitAndRebateVO> profitAndRebateList = productDTO.getProfitAndRebateList();
			if(b&&profitAndRebateList.size()>0){
				for (int i = 0; i < profitAndRebateList.size(); i++) {
					profitAndRebateList.get(i).setRebate(null);
				}
			}
			
			String summary = productDTO.getSummary();
			String titil = "http://www-stg.superfa.cn";

			String replaceAll = summary.replaceAll(titil, "");

			productDTO.setSummary(replaceAll);

			// 判断是否为分销，如果分销则判断用户权限
			if (productDTO != null
					&& productDTO.getCorpType() == Constants.FP_CORP_TYPE_PRIVATE) {
				// UserDTO user = getSession(true).getUser();
				if (! user.getManagerId().equals(productDTO.getCorpId() )
						&& !user.getId().equals(productDTO.getCorpId())) {
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("product is not exists");
					return null;
				}
			}

			ProductAttachmentDTO attachment = new ProductAttachmentDTO();
			attachment.setpId(id);
			List<ProductAttachmentDTO> productAttachments = productService
					.getProductAttachments(attachment);
			// 附件列表
			if (productAttachments == null) {
				productAttachments = new ArrayList<ProductAttachmentDTO>();
			}
			productDTO.setProductAttachments(productAttachments);
			logger.info("=====view success====");
			return productDTO;
		}
	}

	// 募集规模 金额中文换算
	public String getMoneyRender(BigDecimal bd) {
		try {
			if (bd.compareTo(new BigDecimal(1)) == -1) {
				return "-";
			} else if (bd.divide(new BigDecimal(100000000)).compareTo(
					new BigDecimal(1)) != -1) {
				return bd.divide(new BigDecimal(100000000)) + "亿元";
			} else if (bd.divide(new BigDecimal(10000))
					.compareTo(new BigDecimal(1)) != -1) {
				return bd.divide(new BigDecimal(10000)) + "万元";
			} else {
				return bd + "元";
			}
		} catch (Exception e) {
			log.error("getMoneyRender",e);
		}
		return bd+"";
	}

	/**
	 * 发送对比邮件
	 * 
	 * @return
	 */
	@RequestMapping("/sendEmailPro")
	@ResponseBody
	public ResultMap sendEmailPro(HttpServletRequest request,
			HttpServletResponse respons, String code, String email, String type) {
		ResultMap result = new ResultMap();
		try {
			UserDTO user = getSession(true).getUser();
			if (user == null) {
				result.setStatus(STATUS.NEED_LOGIN);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("Need login");
				result.setAttribute(Constants.ResultMessage, "未登录,请先登录");
				return result;
			}
			if (StringUtils.isBlank(code) || code.split(",").length <= 1
					|| StringUtils.isBlank(type) || StringUtils.isBlank(email)) {
				logger.info("==>warn messang:STATUS_CODE_PARAMETERS_LOSE ");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}

			if (!StringUtil.isEmail(email)) { // 邮箱不正确
				logger.info("==>warn messang:email is error ");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_EMAIL_ERROR);
				return result;
			}
			// 对比多个
			String[] allCode = code.split(",");
			HashMap<String, Object> hm = new HashMap<String, Object>();
			String zuheType = "";
			if (type.equals("02") || type.equals("03") || type.equals("06")) {
				if (type.equals("02") || type.equals("03")) {
					zuheType = "02,03";
				} else if (type.equals("06")) {
					zuheType = "06";
				}
				// 拼接信托资管
				for (int i = 0; i < allCode.length; i++) {
					ProductDetailPageDTO productDTO = getXintuoDetail(
							allCode[i], result, user);
					if (productDTO == null) {
						return result;
					}
					if (!zuheType.contains(productDTO.getProductType())) {
						logger.info("==>warn messang:type is error ");
						result.setStatus(STATUS.ERROR);
						result.setStatusCode(ResultMap.STATUS_CODE_PROTYPE_DIFFER);
						return result;
					}
					// 写入邮件模板数据
					if (type.equals("02") || type.equals("03")) {
						getXtzgEmailInfo(hm, productDTO);
					} else if (type.equals("06")) {
						getPevcEmailInfo(hm, productDTO);
					}

				}
			} else {// 产品类型不存在 不支持私募对比
				logger.info("==>warn messang:type is error ");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PROTYPE_NOT_EXIST);
				return result;
			}
			//发送邮件的内容
			Map<String, Object> message = null;
			if (type.equals("02") || type.equals("03")) {
				message = MessageUtil.getMessage("CompareEmailTemplate",
						"productCompareDetailxtzg", hm);
			} else if (type.equals("06")) {
				message = MessageUtil.getMessage("CompareEmailTemplate",
						"productCompareDetailpevc", hm);
			}
			//发送邮件
			String title = (String) message.get(MessageUtil.KEY_TITLE);
			String content = (String) message.get(MessageUtil.KEY_CONTENT);
			MessageMailDTO mail = new MessageMailDTO();
			mail.setFpMailContent(content);
			mail.setFpMailTitle(title);
			mail.setFpMailTo(email);
			mail.setFpMailType("CompareProductEmail");
			mail.setFpMailSendStatus(Constants.message_status_not_send);
			mail.setStatus(Constants.status_normal);
			mail.setFpMailSendType(Constants.message_type_now);
			mail.setCreateBy(user.getUserName());
			mail.setUpdateBy(user.getUserName());
			mail.setFpMailSendTimes(0);
			mail.setCreateDate(new Date());
			mail.setUpdateDate(new Date());
			messageService.insertMailInfo(mail);

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			return result;
		} catch (Exception e) {
			logger.warn("==>warn messang:", e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}

	/**
	 * 根据产品信息-获取同类推荐产品
	 * @return
	 */
	@RequestMapping("/getRecommendProductForProductInfo")
	@ResponseBody
	public ResultMap getRecommendProductForProductInfo(HttpServletRequest request, HttpServletResponse respons,Integer pId) {

		ResultMap result = new ResultMap();
		try {
			log.info("In getRecommendProductForProductInfo end!");
			if (pId == null) {

				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			ProductDetailPageDTO productDTO = productService.getProductView(pId);
			String pType = productDTO.getProductType();
			String pInvestOwner = productDTO.getInvestOwner();
			Integer pDueTime = productDTO.getDueTime();

			BigDecimal minimumAmount = productDTO.getMinimumAmount();
			String pAnnualRevenueExpectStart = productDTO.getProfit()== null? new ProductAnnualRevenueDTO().getExpectAnnualRevenue():productDTO.getProfit().getExpectAnnualRevenue();
			String pAnnualRevenueExpectEnd = productDTO.getProfitHight()== null? new ProductAnnualRevenueDTO().getExpectAnnualRevenue():productDTO.getProfitHight().getExpectAnnualRevenue();
			Double pRabateProfitStart = productDTO.getProfit()== null? new ProductAnnualRevenueDTO().getRebate():productDTO.getProfit().getRebate();
			Double pRabateProfitEnd = productDTO.getProfitHight()== null? new ProductAnnualRevenueDTO().getRebate():productDTO.getProfitHight().getRebate();
			log.info("In getRecommendProductForProductInfo pType:!"+pType);
			log.info("In getRecommendProductForProductInfo pInvestOwner:!"+pInvestOwner);
			log.info("In getRecommendProductForProductInfo pDueTime!"+pDueTime);
			log.info("In getRecommendProductForProductInfo minimumAmount!"+minimumAmount);
			log.info("In getRecommendProductForProductInfo AnnualRevenue!"+pAnnualRevenueExpectStart+"~"+pAnnualRevenueExpectEnd);
			log.info("In getRecommendProductForProductInfo Rebate!"+pRabateProfitStart+"~"+pRabateProfitEnd);



			Map<String,Object> map = new HashMap<String, Object>();
			map.put("pInvestOwner",pInvestOwner);
			map.put("pDueTime",pDueTime);
			map.put("pMinimumAmount",minimumAmount);
			map.put("pAnnualRevenueExpectStart",pAnnualRevenueExpectStart);
			map.put("pAnnualRevenueExpectEnd",pAnnualRevenueExpectEnd);
			map.put("pRabateProfitStart",pRabateProfitStart);
			map.put("pRabateProfitEnd",pRabateProfitEnd);
			map.put("pType",pType);
			map.put("pId",pId);

			List<ProductDTO> productList = this.productService.getRecommendProductForProductInfo(map);

			result.setAttribute("list",productList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("In getRecommendProductForProductInfo error:", e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	public void getPevcEmailInfo(HashMap<String, Object> hm,
			ProductDetailPageDTO productDTO) {
		// 产品名称
		hm.put("productName",
				(hm.get("productName") == null ? "" : hm.get("productName"))
						+ "<td style=\"width:250px\">"
						+ productDTO.getProductName() + "</td>");
		// 预期收益
		List<ProductProfitAndRebateVO> profitAndRebateList = productDTO
				.getProfitAndRebateList();
		String profitAndRebate = "";
		for (int j = 0; j < profitAndRebateList.size(); j++) {
			try {
				if(!StringUtils.isBlank(profitAndRebateList.get(j).getExpectAnnualRevenue())&&!profitAndRebateList.get(j).getExpectAnnualRevenue().contains("%"))
					profitAndRebateList.get(j).setExpectAnnualRevenue(profitAndRebateList.get(j).getExpectAnnualRevenue()+"%");
			} catch (Exception e) {
			}
			profitAndRebate += profitAndRebateList.get(j).getAmountDisplay()
					+ ":" + profitAndRebateList.get(j).getExpectAnnualRevenue();
		}
		hm.put("profitAndRebate",
				(hm.get("profitAndRebate") == null ? "" : hm
						.get("profitAndRebate"))
						+ "<td style=\"width:250px\">"
						+ profitAndRebate + "</td>");
		// 收益分成
		hm.put("peRevenueSharing",
				(hm.get("peRevenueSharing") == null ? "" : hm
						.get("peRevenueSharing"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeRevenueSharing() == null ? ""
						: productDTO.getPeRevenueSharing()) + "</td>");
//		// 返佣
//		String rebate = "";
//		if ("1".equals(productDTO.getCorpType())) {
//			rebate = "-";
//		} else {
//			ProductAnnualRevenueDTO profitHight = productDTO.getProfitHight();
//			if ("1".equals(profitHight.getpIsAgreement())) {
//				rebate = "协议价";
//			} else {
//				rebate = profitHight.getRebate();
//			}
//		}
//		hm.put("rebate", (hm.get("rebate") == null ? "" : hm.get("rebate"))
//				+ "<td style=\"width:250px\">" + rebate + "</td>");
		// 认购费
		hm.put("peSubscriptionFee",
				(hm.get("peSubscriptionFee") == null ? "" : hm
						.get("peSubscriptionFee"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeSubscriptionFee() == null ? ""
						: productDTO.getPeSubscriptionFee()) + "</td>");
		// 管理费
		hm.put("peManagementExpense",
				(hm.get("peManagementExpense") == null ? "" : hm
						.get("peManagementExpense"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeManagementExpense() == null ? ""
						: productDTO.getPeManagementExpense()) + "</td>");
		// 期限
		hm.put("dueTime",
				(hm.get("dueTime") == null ? "" : hm.get("dueTime"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getDueTime() == null ? "" : productDTO
						.getDueTime()) + "个月</td>");
		// 基金类型
		hm.put("peFundShape",
				(hm.get("peFundShape") == null ? "" : hm.get("peFundShape"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeFundShape() == null ? "" : productDTO
						.getPeFundShape()) + "</td>");
		// 组织形式
		hm.put("peOrganizeShape",
				(hm.get("peOrganizeShape") == null ? "" : hm
						.get("peOrganizeShape"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeOrganizeShape() == null ? ""
						: productDTO.getPeOrganizeShape()) + "</td>");
		// 发行机构
		hm.put("investOwner",
				(hm.get("investOwner") == null ? "" : hm.get("investOwner"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getInvestOwner() == null ? "" : productDTO
						.getInvestOwner()) + "</td>");
		//管理机构
		hm.put("peManageOrg",
				(hm.get("peManageOrg") == null ? "" : hm.get("peManageOrg"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPeManageOrg() == null ? "" : productDTO
						.getPeManageOrg()) + "</td>");
		// 起购金额
		hm.put("minimumAmount",
				(hm.get("minimumAmount") == null ? "" : hm.get("minimumAmount"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getMinimumAmount() == null ? "" : productDTO
						.getMinimumAmount()) + "</td>");
		
		// 募集规模
		hm.put("allIssuingScale",
				(hm.get("allIssuingScale") == null ? "" : hm
						.get("allIssuingScale"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getAllIssuingScale() == null ? ""
						: getMoneyRender(productDTO.getAllIssuingScale())) + "</td>");
		// 发行时间
		hm.put("saleDateStart",
				(hm.get("saleDateStart") == null ? "" : hm.get("saleDateStart"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getSaleDateStart() == null ? ""
						: DateUtil.formatDate(productDTO.getSaleDateStart(),
								"yyyy-MM-dd")) + "</td>");
//		// 大小配比
//		hm.put("pSizeRatioExplain",
//				(hm.get("pSizeRatioExplain") == null ? "" : hm
//						.get("pSizeRatioExplain"))
//						+ "<td style=\"width:250px\">"
//						+ (productDTO.getpSizeRatioExplain() == null ? ""
//						: productDTO.getpSizeRatioExplain()) + "</td>");
		// 募集说明
		hm.put("pRecruitmentSummary",
				(hm.get("pRecruitmentSummary") == null ? "" : hm
						.get("pRecruitmentSummary"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getpRecruitmentSummary() == null ? ""
						: productDTO.getpRecruitmentSummary()) + "</td>");
	}

	public void getXtzgEmailInfo(HashMap<String, Object> hm,
			ProductDetailPageDTO productDTO) {
		// 产品名称
		hm.put("productName",
				(hm.get("productName") == null ? "" : hm.get("productName"))
						+ "<td style=\"width:250px\">"
						+ productDTO.getProductName() + "</td>");
		// 预期收益
		List<ProductProfitAndRebateVO> profitAndRebateList = productDTO
				.getProfitAndRebateList();
		String profitAndRebate = "";
		for (int j = 0; j < profitAndRebateList.size(); j++) {
			try {
				if(!StringUtils.isBlank(profitAndRebateList.get(j).getExpectAnnualRevenue())&&!profitAndRebateList.get(j).getExpectAnnualRevenue().contains("%"))
					profitAndRebateList.get(j).setExpectAnnualRevenue(profitAndRebateList.get(j).getExpectAnnualRevenue()+"%");
			} catch (Exception e) {
			}
			profitAndRebate += profitAndRebateList.get(j).getAmountDisplay()
					+ ":" + profitAndRebateList.get(j).getExpectAnnualRevenue();
		}
		hm.put("profitAndRebate",
				(hm.get("profitAndRebate") == null ? "" : hm
						.get("profitAndRebate"))
						+ "<td style=\"width:250px\">"
						+ profitAndRebate + "</td>");
//		// 返佣
//		String rebate = "";
//		if ("1".equals(productDTO.getCorpType())) {
//			rebate = "-";
//		} else {
//			ProductAnnualRevenueDTO profitHight = productDTO.getProfitHight();
//			if ("1".equals(profitHight.getpIsAgreement())) {
//				rebate = "协议价";
//			} else {
//				rebate = profitHight.getRebate();
//			}
//		}
//		hm.put("rebate", (hm.get("rebate") == null ? "" : hm.get("rebate"))
//				+ "<td style=\"width:250px\">" + rebate + "</td>");
		// 期限
		hm.put("dueTime",
				(hm.get("dueTime") == null ? "" : hm.get("dueTime"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getDueTime() == null ? "" : productDTO
						.getDueTime()) + "个月</td>");
		// 投资方向 类型
		hm.put("investType",
				(hm.get("investType") == null ? "" : hm.get("investType"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getInvestDesc() == null ? "" : productDTO
						.getInvestDesc()) + "</td>");
		// 付息方式
		hm.put("paymentInterestType",
				(hm.get("paymentInterestType") == null ? "" : hm
						.get("paymentInterestType"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getPaymentInterestTypeDesc() == null ? ""
						: productDTO.getPaymentInterestTypeDesc()) + "</td>");
		// 机构
		hm.put("investOwner",
				(hm.get("investOwner") == null ? "" : hm.get("investOwner"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getInvestOwner() == null ? "" : productDTO
						.getInvestOwner()) + "</td>");
		// 募集规模
		hm.put("allIssuingScale",
				(hm.get("allIssuingScale") == null ? "" : hm
						.get("allIssuingScale"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getAllIssuingScale() == null ? ""
						: getMoneyRender(productDTO.getAllIssuingScale()))
								+ "</td>");
		// 发行时间
		hm.put("saleDateStart",
				(hm.get("saleDateStart") == null ? "" : hm.get("saleDateStart"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getSaleDateStart() == null ? ""
						: DateUtil.formatDate(productDTO.getSaleDateStart(),
								"yyyy-MM-dd")) + "</td>");
		// 大小配比
		hm.put("pSizeRatioExplain",
				(hm.get("pSizeRatioExplain") == null ? "" : hm
						.get("pSizeRatioExplain"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getpSizeRatioExplain() == null ? ""
						: productDTO.getpSizeRatioExplain()) + "</td>");
		// 募集说明
		hm.put("pRecruitmentSummary",
				(hm.get("pRecruitmentSummary") == null ? "" : hm
						.get("pRecruitmentSummary"))
						+ "<td style=\"width:250px\">"
						+ (productDTO.getpRecruitmentSummary() == null ? ""
						: productDTO.getpRecruitmentSummary()) + "</td>");
	}
	
	/**
	 * 对比接口
	 * 
	 * @return
	 */
	@RequestMapping("/compare")
	@ResponseBody
	public ResultMap compare(HttpServletRequest request,HttpServletResponse respons,String code) {
		UserDTO user = getSession(true).getUser();//当前登录用户
		if(user==null){
			user = new UserDTO();
		}
		ResultMap result = new ResultMap();
		try {
			if (StringUtils.isBlank(code)) {
				logger.info("==>warn messang:STATUS_CODE_PARAMETERS_LOSE ");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			List<ProductBasicInfoDTO> l=new ArrayList<ProductBasicInfoDTO>();
			String[] codeArray=code.split(",");
			for (int i = 0; i < codeArray.length; i++) {
				if(StringUtils.isBlank(codeArray[i])){
					continue;
				}
				ProductBasicInfoDTO basicInfo = productService.queryAllProductBasicInfo(codeArray[i]);
				if(basicInfo==null){//没有查询到该产品信息 直接返回空对象
					ProductBasicInfoDTO b=new ProductBasicInfoDTO();
					l.add(b);
					continue;
				}
				//分割summary
				String summary = basicInfo.getSummary();
				String titil="http://www-stg.superfa.cn";
				String summaryRep = summary.replaceAll(titil,"").replace("---输入内容---", "").replace("---输入内容--", "");
				HashMap<String, String> splitSummary = splitSummary(summaryRep);
				basicInfo.setFxkz(splitSummary.get("fxkz"));
				basicInfo.setSummary(com.alibaba.fastjson.JSONArray.toJSONString(splitSummary));
				//查询当前产品的收益区间和返佣区间
				List<ProductProfitAndRebateVO> profitRebateList = productService.getProductProfitAndRebateList(basicInfo.getId(),null);
				for(ProductProfitAndRebateVO profitVo:profitRebateList){
					if(user == null||StringUtil.isNullOrEmptyStr(user.getLoginName())){
						profitVo.setRebate(null);
						profitVo.setRebateDesc("登录可见");
					}else if("1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole())){
						profitVo.setRebate(null);
						profitVo.setRebateDesc("认证可见");
					}
				}
				basicInfo.setProfitRebateList(profitRebateList);
				l.add(basicInfo);
			}
			
			result.setAttribute("list", l);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			return result;
		} catch (Exception e) {
			logger.warn("==>warn messang:" + e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}

	}
	
}


